//
//  RecordListView.swift
//  Scaner
//
//  Created by liyahao on 2025/4/15.
//

import SwiftUI

struct RecordListView: View {
    @StateObject var vModel = AudioVModel()
    @State var showRecord = false
    
    var body: some View {
        ScrollView {
            ForEach(vModel.models) { model in
                NavigationLink {
                    RecordDetailView(model: model)
                } label: {
                    RecordListRow(model: model) {
                        vModel.removeData(model: model)
                    }
                }
            }
        }
        .navigationTitle("我的录音")
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button {
                    showRecord.toggle()
                } label: {
                    Image(systemName: "plus")
                        .foregroundStyle(Color(.darkText))
                }
            }
        }
        .sheet(isPresented: $showRecord) {
            RecordingView()
        }
    }
}

struct RecordListRow: View {
    var model: AudioFiles
    var action: () -> Void
    var body: some View {
        VStack {
            HStack {
                VStack(alignment: .leading, spacing: 8) {
                    Text(model.name)
                        .font(.title3.weight(.medium))
                        .foregroundStyle(Color(.darkText))
                    
                    if let asr = model.asr {
                        Text(asr)
                            .font(.system(size: 14))
                            .foregroundStyle(Color(.darkText))
                            .lineSpacing(3)
                            .lineLimit(2)
                            .multilineTextAlignment(.leading)
                    }

                    HStack {
                        Text(model.duration.formatTime)
                            .font(.system(size: 14))
                            .foregroundStyle(Color(.darkText))

                        Spacer()
                        Text(model.tsp.tspFormat() ?? "")
                            .font(.system(size: 14))
                            .foregroundStyle(Color(.systemGray))
                    }
                }
                Spacer()
                Button { action() } label: {
                    Image(systemName: "trash")
                        .font(.system(size: 14))
                        .foregroundStyle(Color(.darkText))
                }
            }
            .padding(.vertical, 10)
            .padding(.horizontal)
            
            Divider()
        }
    }
}

#Preview {
    NavigationView {
        RecordListView()
    }
}
